package com.vip.iot.service;

import com.vip.iot.protocol.mqtt.IMqttInstance;
import com.vip.iot.protocol.mqtt.MqttInstanceImpl;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 发送数据到MQTT服务器工具
 *
 * @author wgb
 * @date 2020/6/17 18:09
 */
@Slf4j
@Component
public class MqttPubMsgService {
    /**
     * MQTT服务端 ip:port
     */
    @Value("${mqtt.server.url}")
    private String url;
    /**
     * MQTT登录账户名
     */
    @Value("${mqtt.server.username}")
    private String username;
    /**
     * 密码
     */
    @Value("${mqtt.server.password}")
    private String password;
    /**
     * 作为MQTT实例单例模式，提供单个MQTT连接
     */
    private static IMqttInstance client = null;

    public MqttPubMsgService() {
    }

    public MqttPubMsgService(String url, String username, String password) {
        this.url = url;
        this.username = username;
        this.password = password;
    }

    /**
     * 单例模式，获取IMqttClient实现类MqttClientImpl
     *
     * @return
     */
    public IMqttInstance getMqttClient() {
        if (client == null) {
            client = new MqttInstanceImpl();
            client.init(url, username, password);
        }
        return client;
    }

    /**
     * 发送消息到MQTT, 用作测试时的使用
     *
     * @param topic   主题
     * @param message 消息
     * @return 发送结果
     */
    public Map<String, String> sentMessageToMqtt(String topic, String message) {
        IMqttInstance mqttClient = getMqttClient();
        Map<String, String> result = new HashMap<>();
        try {
            mqttClient.publish(topic, message, 0);
            result.put("message", "发送消息到MQTT成功！");
            result.put("code", "1");
        } catch (MqttException e) {
            log.error(e.getMessage());
            result.put("message", "发送消息到MQTT失败！");
            result.put("code", "0");
        }
        return result;
    }

}
